/**
 * Created by a1 on 2017/10/26.
 */
"use strict";
var fs = require('fs');
var formidable = require('formidable');
var common = require('../models/common.js');
var BookModel = require('../models/Book.js');//书本Schema
var BookupdateModel = require('../models/Bookupdate.js');//章节Schema
var BookshelfModel=require('../models/Bookshelf.js');

exports.catalogKey=function(req,res){
    let session=false;
    if(req.session.username){
        session=true;
    }
    if(!isNaN(req.params.key)){
        res.render('catalog',{
            page:'catalog',
            bid:req.params.key,
            session:session
        })
    }else {
        res.render('error',{
            page:'error'
        })
    }
};
exports.getChapter=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let bid=fields.bid;
        let seq=fields.seq;
        let sort=seq=='true'?1:-1;
        BookupdateModel.findFn({bid:bid},{'buid':sort},function(err,docs){
            if(err){
                res.json({"msg":'失败',"code":0,info:{}});
                return;
            }
            res.json({"msg":'成功',"code":1,info:docs});
        });
    });
};
exports.setBookChapter=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files) {
        let bid=fields.bid;
        let cid=fields.cid;
        let cName=fields.cName;
        BookshelfModel.findSortOne({uid: req.session.uid}, {bsid: 1}, function (err, docs) {
            let i1=true;
            let i2=true;
            let key=true;
            for(let i=0;i<docs['bookshelf'].length;i++){
                for(let j=0;j<docs['bookshelf'][i]['books'].length;j++){
                    if(docs['bookshelf'][i]['books'][j]['bid']==bid){
                        i1=i;
                        i2=j;
                        key=false;
                        break;
                    }
                }
            }
            if(key){
                res.json({"msg":'成功',"code":0});
            }else{
                let shelf='{"bookshelf.'+i1+'.books.'+i2+'.chapter":'+cid+',"bookshelf.'+i1+'.books.'+i2+'.chapterNmae":"'+cName+'","bookshelf.'+i1+'.books.'+i2+'.readTime":'+new Date().getTime()+'}';
                let setObj=JSON.parse(shelf);
                BookshelfModel.updateFn({uid: req.session.uid},{$set:setObj},function(err,docs1){
                    res.json({"msg":'成功',"code":1});
                });
            }
        });
    });
};